package com.andyliu.realm;

import com.andyliu.sys.service.UserService;
import com.andyliu.vo.UserVO;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * ClassName: UserRealm
 * Description: TODO
 * date: 2021/1/21 3:45 下午
 *
 * @author andyliu
 * @since JDK 1.8
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken token_=(UsernamePasswordToken)token;
        String  userName = token_.getUsername();
        String pwd = new String(token_.getPassword());
        UserVO user = userService.selectUser(userName, null);
        if(user==null){
            throw new UnknownAccountException();
        }
        if(!user.getPwd().equals(pwd)){
            throw new AuthenticationException();
        }

        AuthenticationInfo info = new SimpleAuthenticationInfo(userName,pwd,null,getName());
        return info;
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = principalCollection.getPrimaryPrincipal().toString();
        UserVO user = userService.selectUser(userName,null);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole("admin");
        return info;
    }
}
